import os
import yaml
import json
import logging
from typing import Dict, List, Optional
from backend.DSL.executor.dsl_executor import DSLExecutor

logger = logging.getLogger(__name__)

class DSLHandler:
    """DSL处理器 - 处理DSL相关的查询和执行"""
    
    def __init__(self):
        self.workspace_root = "/root/workspace/AI_logging_engine"
        self.index_path = f"{self.workspace_root}/backend/DSL/index/flow_index.yaml"
        self.flows_dir = f"{self.workspace_root}/backend/DSL/flows"
        self.out_dir = f"{self.workspace_root}/backend/DSL/out"
        
        # 创建DSL执行器，只提供必要的参数
        self.executor = DSLExecutor(
            workspace_root=self.workspace_root,
            out_dir=self.out_dir
        )
        
    def load_flow_index(self) -> Dict:
        """加载Flow索引"""
        try:
            with open(self.index_path, 'r', encoding='utf-8') as f:
                return yaml.safe_load(f)
        except Exception as e:
            logger.error(f"加载Flow索引失败: {e}")
            return {"flows": []}
            
    async def match_flow(self, query: str, ai_analyzer) -> Dict:
        """使用AI匹配合适的Flow"""
        try:
            # 加载Flow索引
            flow_index = self.load_flow_index()
            
            # 构建提示词
            prompt = f"""作为一个诊断流程匹配专家，你的任务是从已有的Flow列表中，为用户的问题找到最合适的诊断流程。

用户问题: {query}

当前可用的Flow列表（这是完整的列表，不要臆测其他Flow的存在）:
{yaml.dump(flow_index, allow_unicode=True)}

请仔细分析用户问题与现有Flow的匹配度。如果没有找到合适的Flow（匹配度低于70%），请明确指出。

请以JSON格式返回，格式如下：

1. 如果找到合适的Flow:
{{
    "found": true,
    "matched_flow": {{
        "id": "Flow ID",
        "file": "Flow文件名",
        "confidence": 0.95,  # 匹配置信度(0.7-1.0)
        "reason": "选择原因，包括匹配点和可能的局限性"
    }}
}}

2. 如果没有找到合适的Flow:
{{
    "found": false,
    "reason": "详细解释为什么现有Flow都不适合",
    "suggestion": "对用户的建议，例如需要怎样的Flow来解决该问题"
}}

注意：
1. 严格基于Flow的description进行匹配
2. 不要臆测Flow的功能范围
3. 宁可返回"未找到"，也不要勉强匹配不合适的Flow
"""
            # 调用AI进行匹配
            response = await ai_analyzer.ask_question(prompt)
            answer = response['answer']
            
            # 清理可能的Markdown代码块标记
            if answer.startswith("```"):
                # 移除第一行的 ```json 或类似标记
                answer = answer.split("\n", 1)[1]
            if answer.endswith("```"):
                # 移除最后一行的 ```
                answer = answer.rsplit("\n", 1)[0]
            
            # 清理并解析JSON
            answer = answer.strip()
            logger.info(f"清理后的JSON: {answer}")
            
            result = json.loads(answer)
            
            # 检查是否找到匹配的Flow
            if not result.get('found', False):
                return {
                    'error': '未找到匹配的Flow',
                    'reason': result.get('reason', ''),
                    'suggestion': result.get('suggestion', '')
                }
            
            return result['matched_flow']
            
        except Exception as e:
            logger.error(f"Flow匹配失败: {e}")
            return None
            
    async def execute_flow(self, flow_id: str, log_file: str) -> Dict:
        """执行Flow分析"""
        try:
            # 加载Flow定义
            flow_path = os.path.join(self.flows_dir, flow_id)
            with open(flow_path, 'r', encoding='utf-8') as f:
                flow_def = yaml.safe_load(f)
                
            # 执行Flow分析
            context = {
                "log_file": log_file,
                "auto_approve": True
            }
            
            result = await self.executor.run(flow_def, context)
            return result
            
        except Exception as e:
            logger.error(f"Flow执行失败: {e}")
            return None
            
    async def analyze_result(self, result: Dict, ai_analyzer) -> Dict:
        """分析Flow执行结果"""
        try:
            # 构建分析提示词
            prompt = f"""分析以下DSL执行结果，提供问题诊断和解决方案。

执行轨迹:
{json.dumps(result['trace'], indent=2, ensure_ascii=False)}

最终状态: {result['final_state']}
状态消息: {result.get('final_state_message', '')}
证据数量: {len(result.get('evidence', []))}

请提供：
1. 问题定位：根据执行轨迹和最终状态，说明问题的具体原因
2. 证据分析：解释关键日志证据的含义
3. 解决方案：给出具体的解决建议
4. 预防措施：如何避免类似问题

请用中文回答，提供具体可操作的建议。
"""
            # 调用AI进行分析
            response = await ai_analyzer.ask_question(prompt)
            return {
                'analysis': response['answer'],
                'raw_result': result
            }
            
        except Exception as e:
            logger.error(f"结果分析失败: {e}")
            return None
            
    async def process_dsl_query(self, query: str, log_file: str, ai_analyzer) -> Dict:
        """处理DSL查询的完整流程"""
        try:
            # 1. 匹配合适的Flow
            match_result = await self.match_flow(query, ai_analyzer)
            if isinstance(match_result, dict) and 'error' in match_result:
                # 没有找到匹配的Flow，返回分析结果
                return {
                    'status': 'no_match',
                    'error': match_result['error'],
                    'reason': match_result['reason'],
                    'suggestion': match_result['suggestion']
                }
            
            # 2. 执行Flow分析
            result = await self.execute_flow(match_result['file'], log_file)
            if not result:
                return {'error': 'Flow执行失败'}
                
            # 3. 分析执行结果
            analysis = await self.analyze_result(result, ai_analyzer)
            if not analysis:
                return {'error': '结果分析失败'}
                
            return {
                'status': 'success',
                'matched_flow': match_result,
                'analysis': analysis['analysis'],
                'raw_result': analysis['raw_result']
            }
            
        except Exception as e:
            logger.error(f"DSL查询处理失败: {e}")
            return {'error': f'DSL查询处理失败: {str(e)}'}
            return {'error': f'DSL查询处理失败: {str(e)}'}